package myutils

import (
	"crypto/tls"
	"cybeego/models"
	"fmt"
	"net/http"
	"time"

	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

var a = make([]string, 0, 10)

func init() {
	logs.Debug("https init is running!")

	logs.Debug("https init is ending! a", a)

}

func InitHttps() {
	o := orm.NewOrm()
	var domain []models.Domain
	o.QueryTable("domain").All(&domain)
	for i, d := range domain {
		logs.Debug("domain i is", i, d.Id, d.Title)
		duetime := CheckHttpsBase(d.Title)
		logs.Debug("d.Id duetime 更新：", d.Id, duetime)
		d.DueTime = duetime
		o.Update(&d)
	}
}

func CheckHttps() {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}

	o := orm.NewOrm()
	var domain []models.Domain
	o.QueryTable("domain").All(&domain)
	for i, d := range domain {
		logs.Debug("domain i is", i, d.Id, d.Title)
		// logs.Debug("domain d.Id is", d.Id)
		// logs.Debug("domain d.Title", d.Title)

		seedUrl := d.Title
		resp, err := client.Get(seedUrl)
		err2 := resp.Body.Close()
		if err2 != nil {
			logs.Info(" 请求失败")
			panic(err2)
		}
		defer resp.Body.Close()
		if err != nil {
			logs.Info(seedUrl, " 请求失败")
			panic(err)
		}

		//fmt.Println(resp.TLS.PeerCertificates[0])
		certInfo := resp.TLS.PeerCertificates[0]
		fmt.Println("过期时间:", certInfo.NotAfter)
		fmt.Println("组织信息:", certInfo.Subject)
	}

}

func CheckHttpsBase(url string) time.Time {

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}

	seedUrl := url
	resp, err := client.Get(seedUrl)
	defer resp.Body.Close()

	if err != nil {
		fmt.Errorf(seedUrl, " 请求失败")
		panic(err)
	}

	//fmt.Println(resp.TLS.PeerCertificates[0])
	certInfo := resp.TLS.PeerCertificates[0]
	// fmt.Println("过期时间:", certInfo.NotAfter)
	// fmt.Println("组织信息:", certInfo.Subject)
	return certInfo.NotAfter

}
